package com.contract.commonlib.util;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.blankj.utilcode.util.Utils;


/**
 * Created by fangyufeng on 2016/8/18.
 */
public class DisplayMetricsTool {

    DisplayMetrics mDisplayMetrics;
    static DisplayMetricsTool instance;

    public static DisplayMetricsTool getInstance() {
        if (instance == null) instance = new DisplayMetricsTool();
        return instance;
    }

    public static boolean isOrientationPortrait() {
        return Utils.getApp().getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_PORTRAIT;
    }

    public int getHeightPixels() {
        Context context = Utils.getApp();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return context.getResources().getDisplayMetrics().heightPixels;
        }
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            wm.getDefaultDisplay().getSize(point);
        }
        return point.y;
    }

    public Float getDensity() {
        return getDisplayMetrics().density;
    }

    public int getWidthPixels() {
        return getDisplayMetrics().widthPixels;
    }

    public synchronized DisplayMetrics getDisplayMetrics() {
        if (mDisplayMetrics == null) {
            mDisplayMetrics = new DisplayMetrics();
            WindowManager wm = (WindowManager)
                    Utils.getApp()
                            .getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(mDisplayMetrics);
        }
        return mDisplayMetrics;
    }

    public int getDPsize(float old) {
        return (int) (old * getDensity());
    }


    public int px2dp(float pxValue) {
        return (int) (pxValue / getDensity() + 0.5f);
    }

    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public int getDPByDimin(int id) {
        Resources resources = Utils.getApp().getResources();
        return px2dp(resources.getDimension(id));
    }
}
